import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
Vue.use(Vuex);
// Vuex: 状态管理器

export default new Vuex.Store({
    state: {
        num: 10,
        score: 90,
        cityList: [],
    },
    // 有且只有mutations能修改VueX的状态
    mutations: {
        add(state, payload) {
            console.log(state);
            console.log(payload);
            state.num += payload;
        },
        addCityList(state, payload) {
            state.cityList = payload;
        },
    },
    // 包含异步操作,它不可以直接修改,必须通过mutations才能修改
    actions: {
        getCityList(context, payload) {
            // let payload;
            let arr = ['南昌', '宜春', '南阳', '吉安'];
            setTimeout(() => {
                context.commit('addCityList', arr);
            }, 2000);
            // console.log(context);
            // console.log(payload);
        },
    },

    // 相当于我们组件里面的computed
    getters: {
        cityListLen(state, getters) {
            // console.log(state);
            // console.log(getters);
            return state.cityList.length;
        },
        filterCityList(state) {
            let arr = [];
            for (const key in state.cityList) {
                // console.log(key);
                // console.log(state.cityList[key]);
                // console.log(state.cityList[key].indexOf('南'));
                if (state.cityList[key].indexOf('南') != -1) {
                    // console.log(state.cityList[key]);
                    arr.push(state.cityList[key]);
                }
            }
            return arr;
        },
    },
    modules: {},
    plugins: [createPersistedState()],
});
